// const baseUrl = 'http://127.0.0.1:8000/api/'
// const baseUrl = 'http://192.168.0.2:8000/api/'
// const baseUrl = 'http://47.100.95.58:8000/api/'
const baseUrl = 'http://10.147.20.45:8000/api/'

/**
 * 请求头
 */
function getHeader() {
    var header = {
        // 'content-type': 'application/json',
        // 'content-type': 'application/x-www-form-urlencoded',
        'token':getToken(),
    }
    return header;
}

function getToken() {
    var token 
    token = wx.getStorageSync("token");
    // console.log('请求封装时：'+token);
    return token;
}
/**
 * function: 根据需求处理请求参数：添加固定参数配置等
 * @params 请求参数
 */
function dealParams(params, method) {
    return method === 'POST' ? JSON.stringify(params) : params;
}

const getUrl = (url) => {
    if (url.indexOf('://') == -1) {
        url = baseUrl + url;
    }
    return url
}
/**
 * function: 封装网络请求
 * @url URL地址
 * @params 请求参数
 * @method 请求方式：GET/POST
 * @onSuccess 成功回调
 * @onFailed  失败回调
 */

const http = ({ url = '', param = {}, ...other } = {}) => {
    wx.showLoading({
        mask: 'true',
        title: '请求中，请耐心等待..'
    });

    let timeStart = Date.now();
    console.log(param)
    return new Promise((resolve, reject) => {
        wx.request({
            url: getUrl(url),
            data:  param,
            header: getHeader(),
            ...other,
            complete: (res) => {
                wx.hideLoading();
                console.log(`耗时${Date.now() - timeStart}`);
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    resolve(res.data)
                    if (res.data.code != 2000) {
                        wx.showToast({
                            title: res.data.message,
                            icon: 'none',
                           
                            duration: 2000
                        })
                    }
                } else {
                    reject(res.data)
                }
            }
        })
    })
}



/**
 * 供外部post请求调用  
 */
const post = (url, param = {}) => { return http({ url, param, method: 'POST' }) }
/**
 * 供外部get请求调用
 */
const get = (url, param = {}) => { return http({ url, param }) }

/**
 * 供外部post请求调用  
 */
const put = (url, param = {}) => { return http({ url, param, method: 'PUT' }) }

/**
 * 供外部delete请求调用
 */
const dele = (url, param = {}) => { return http({ url, param, method: 'DELETE' }) }

module.exports = {
    post,
    get,
    put,
    dele
}